﻿// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll().done(function () {
                $("#submission").click(getValues);
            }));
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    function getValues(mouseEvent) {
        var symbol = $("#stocksymbol").val();
        var dateValue = $("#startdate").val();

        var uri = getUri(symbol, dateValue);
        
        var request = new XMLHttpRequest();

        request.open("GET", uri, false);
        request.send();

        var stockInfos = getStockInfos(request.responseText);

        setTable(request.responseText);
        setChart(symbol, new Date(dateValue), null, stockInfos);
    }

    function getUri(symbol, dateValue) {
        var date = new Date(dateValue);
        var today = new Date();

        var uri = "http://ichart.finance.yahoo.com/table.csv";
        uri += "?s=" + symbol;
        uri += "&a=" + date.getMonth();
        uri += "&b=" + date.getDate();
        uri += "&c=" + date.getFullYear();
        uri += "&g=d";

        return uri;
    }

    function setChart(name, date, type, stockInfos) {
        var stockData = new Array(stockInfos.length);

        for (var i = 0; i < stockData.length; i++) {
            stockData[i] = [Date.UTC(stockInfos[i].date.getFullYear(), stockInfos[i].date.getMonth(), stockInfos[i].date.getDate()), stockInfos[i].closePrice];
        }


        var Chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                type: 'spline'
            },

            title: {
                text: "Stock price for " + name + " since " + date
            },

            xAxis: {
                type: 'datetime',
                title: {
                    text: 'Date'
                }
            },

            yAxis: {
                type: 'float',
                title: {
                    text: 'Stock price'
                }
            },

            series: [{
                name: "Closing Price",
                marker: {
                    radius: 4
                },
                lineWidth: 4,
                data: stockData
            }]
        });
    }

    function setTable(csv) {
        var table = $("#response")[0];
        for (var i = table.rows.length - 1; i > -1; i--) table.deleteRow(i);

        var lines = csv.split('\n');

        var headerValues = lines[0].split(',');

        var oTHead = table.createTHead();

        var headerRow = oTHead.insertRow(-1);
        for (var i = 0; i < headerValues.length; i++) {
            var div = document.createElement("div"),
                txt = document.createTextNode(headerValues[i]);
            div.appendChild(txt);

            var cell = headerRow.insertCell(i);
            cell.appendChild(div);
        }

        for (var i = lines.length - 1; i > 0; i--) {
            var values = lines[i].split(',');

            var row = table.insertRow();
            for (var j = 0; j < values.length; j++) {
                var div = document.createElement("div"),
                    txt = document.createTextNode(values[j]);
                div.appendChild(txt);

                var cell = row.insertCell(j);
                cell.appendChild(div);
            }
        }
    }
    
    function getStockInfos(csv) {
        var lines = csv.split('\n');

        var myStocks = new Array();

        for (var i = lines.length - 1; i > 0; i--) {
            var values = lines[i].split(',');

            if (values.length == 7) {
                var stock = new StockInfo(values);
                myStocks[myStocks.length] = stock;
            }
        }

        return myStocks;
    }

    var StockInfo = WinJS.Class.define(function (values) {
        this.date = new Date(values[0]);
        this.openPrice = parseFloat(values[1]);
        this.highPrice = parseFloat(values[2]);
        this.lowPrice = parseFloat(values[3]);
        this.closePrice = parseFloat(values[4]);
        this.volume = parseFloat(values[5]);
        this.adjustedClosePrice = parseFloat(values[6]);
    },
    {
        date: new Date(),
        openPrice: 0,
        highPrice: 0,
        lowPrice: 0,
        closePrice: 0,
        volume: 0,
        adjustedClosePrice: 0
    });

    app.start();
})();
